package com.micro.platform.oauth.rpc;

import com.micro.platform.oauth.component.RsaComponent;
import com.micro.platform.oauth.dto.RSAPrivateKeyDTO;
import com.micro.platform.oauth.dto.RefreshTokenInfoDTO;
import com.micro.platform.oauth.dto.TokenInfoDTO;
import com.micro.platform.oauth.enums.OauthErrorCodeEnum;
import com.micro.platform.oauth.framework.OauthManager;
import com.micro.platform.oauth.framework.constants.OauthConstants;
import com.micro.platform.oauth.framework.domain.AccessToken;
import com.micro.platform.oauth.framework.domain.RefreshToken;
import com.micro.platform.oauth.framework.exception.OauthException;
import com.micro.platform.starter.exception.BusinessException;
import com.micro.platform.starter.utils.MapUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@DubboService
public class OauthRpcServiceImpl implements OauthRpcService {

    @Autowired
    private RsaComponent rsaComponent;
    @Autowired
    private OauthManager oauthManager;

    @Override
    public TokenInfoDTO analysisAccessToken(String accessToken) throws BusinessException {
        AccessToken accessTokenObj;
        try{
            accessTokenObj = oauthManager.getAccessToken(accessToken);
        }catch (OauthException ex){
            throw new BusinessException(OauthErrorCodeEnum.AUTHORIZATION_ERROR, ex);
        }
        if(accessTokenObj == null){
            return null;
        }
        Map<String, Object> data = accessTokenObj.getData();
        TokenInfoDTO tokenInfoDTO = new TokenInfoDTO();
        tokenInfoDTO.setUserId(MapUtils.getLong(data, "userId"));
        tokenInfoDTO.setNickName(MapUtils.getString(data, "nickName"));
        tokenInfoDTO.setPhone(MapUtils.getString(data, "phone"));
        tokenInfoDTO.setEmail(MapUtils.getString(data, "email"));
        tokenInfoDTO.setPrivateKey(MapUtils.getString(data, "privateKey"));
        tokenInfoDTO.setPublicKey(MapUtils.getString(data, "publicKey"));
        tokenInfoDTO.setCreateTime(MapUtils.getString(data, "createTime"));
        List<String> apis = MapUtils.getArrayList(data, "apis", String.class);
        if(apis == null){
            apis = Collections.emptyList();
        }
        tokenInfoDTO.setApis(apis);
        return tokenInfoDTO;
    }
}
